package org.dtrd.modules.system.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dtrd.modules.system.entity.bean.qiyeweixin.RobotDetail;
import org.dtrd.modules.system.entity.bean.qiyeweixin.RobotListInfo;
import org.dtrd.modules.system.entity.po.DtrdEntRdRobot;
import org.dtrd.modules.system.entity.request.RobotListRequest;
import org.dtrd.modules.system.entity.request.RobotPageRequest;
import org.dtrd.modules.system.mapper.DtrdEntRdRobotMapper;
import org.dtrd.modules.system.service.IDtrdEntRdRobotService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * <p>
 * 企业微信机器人记录表 服务实现类
 * </p>
 *
 * @author QR
 * @since 2022-03-08
 */
@DS("multi-datasource1")
@Service
public class DtrdEntRdRobotServiceImpl extends ServiceImpl<DtrdEntRdRobotMapper, DtrdEntRdRobot> implements IDtrdEntRdRobotService {

    @Override
    public List<RobotListInfo> getRobotList(RobotListRequest request) {
        List<DtrdEntRdRobot> poList = list();
        List<RobotListInfo> dtoList = new ArrayList<>(poList.size());
        if (!poList.isEmpty()) {
            dtoList = poList.stream().map(RobotListInfo::new).collect(Collectors.toList());
        }
        return dtoList;
    }

    @Override
    public boolean isValidName(String robotName, Integer dataId) {
        LambdaQueryWrapper<DtrdEntRdRobot> wrapper = baseQueryWrapper()
                .eq(DtrdEntRdRobot::getRobotName, robotName)
                .last("limit 1");
        DtrdEntRdRobot robot = getOne(wrapper);
        return robot == null || Objects.equals(robot.getDataId(), dataId);
    }

    @Override
    public String getRobotWebhookurl(Integer robotId) {
        DtrdEntRdRobot robot = getById(robotId);
        if (robot == null) {
            throw new IllegalArgumentException("无效的 robotId");
        }
        return robot.getWebhookurl();
    }

    @Override
    public IPage<RobotListInfo> pageRobot(RobotPageRequest request) {
        LambdaQueryWrapper<DtrdEntRdRobot> queryWrapper = baseQueryWrapper();
        IPage<DtrdEntRdRobot> page = new Page<>(request.getPageNum(), request.getPageSize());
        page = this.page(page, queryWrapper);
        return page.convert(RobotListInfo::new);
    }

    @Override
    public RobotDetail getRobot(Integer dataId) {
        DtrdEntRdRobot dtrdEntRdRobot = getById(dataId);
        return Optional.ofNullable(dtrdEntRdRobot)
                        .map(po -> new RobotDetail().parseFromPO(po))
                        .orElse(null);
    }

    @Override
    public boolean saveOrUpdateRobot(RobotDetail dto) {
        DtrdEntRdRobot po = new DtrdEntRdRobot();
        if(dto.getId() == null){
            po = po.init();
        }
        String webhookurl = dto.getWebhookurl();
        po.setWebhookkey(getKey(webhookurl));
        po.parseFromDTO(dto);
        return saveOrUpdate(po);
    }

    private static String getKey(String webhookurl) {
        String[] strings = webhookurl.split("\\?");
        if (strings.length != 2) {
            throw new IllegalArgumentException("无效的webhookurl");
        }
        // 去除 "key=" 部分
        return strings[1].substring(4);
    }

    @Override
    public boolean removeRobot(Integer dataId) {
        return removeById(dataId);
    }

    private LambdaQueryWrapper<DtrdEntRdRobot> baseQueryWrapper() {
        return Wrappers.lambdaQuery(DtrdEntRdRobot.class);
    }

    private LambdaUpdateWrapper<DtrdEntRdRobot> baseUpdateWrapper() {
        return Wrappers.lambdaUpdate(DtrdEntRdRobot.class)
                        .eq(DtrdEntRdRobot::getIsDel, 0);
    }
}
